﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
namespace PTA
{
    public static class ExtensionUtils
    {
        #region WebControl
        /// <summary>
        /// 查找指定类型的子控件
        /// </summary>
        /// <typeparam name="T">控件的类型</typeparam>
        /// <param name="ctl">控件</param>
        /// <param name="id">要查找的控件的ID</param>
        /// <returns>返回查找到的控件</returns>
        public static T FindControl<T>(this System.Web.UI.Control ctl, string id)
            where T : System.Web.UI.Control
        {
            T result = ctl.FindControl(id) as T;
            return result;
        }

        #region 查找Web控件
        /// <summary>
        /// 查找隐藏控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HiddenField FindHidden(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<HiddenField>(ctl, id);
        }

        /// <summary>
        /// 查找文本控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static TextBox FindTextBox(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<TextBox>(ctl, id);
        }

        /// <summary>
        /// 查找单选控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static RadioButton FindRadioButton(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<RadioButton>(ctl, id);
        }

        /// <summary>
        /// 查找单选控件列表
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static RadioButtonList FindRadioButtonList(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<RadioButtonList>(ctl, id);
        }

        /// <summary>
        /// 查找下拉控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DropDownList FindDropDownList(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<DropDownList>(ctl, id);
        }

        /// <summary>
        /// 查找复选控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static CheckBox FindCheckBox(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<CheckBox>(ctl, id);
        }

        /// <summary>
        /// 查找复选控件列表
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static CheckBoxList FindCheckBoxList(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<CheckBoxList>(ctl, id);
        }

        /// <summary>
        /// 查找列表框
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static ListBox FindListBox(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<ListBox>(ctl, id);
        }

        /// <summary>
        /// 查找按钮
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Button FindButton(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Button>(ctl, id);
        }

        /// <summary>
        /// 查找链接按钮
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static LinkButton FindLinkButton(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<LinkButton>(ctl, id);
        }

        /// <summary>
        /// 查找图片控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static global::System.Web.UI.WebControls.Image FindImage(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<global::System.Web.UI.WebControls.Image>(ctl, id);
        }

        /// <summary>
        /// 查找图片按钮
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static ImageButton FindImageButton(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<ImageButton>(ctl, id);
        }

        /// <summary>
        /// 查找Litel控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Literal FindLiteral(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Literal>(ctl, id);
        }

        /// <summary>
        /// 查找链接
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HyperLink FindHyperLink(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<HyperLink>(ctl, id);
        }

        /// <summary>
        /// 查找标签
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Label FindLabel(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Label>(ctl, id);
        }

        /// <summary>
        /// 查找窗口控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Panel FindPanel(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Panel>(ctl, id);
        }

        /// <summary>
        /// 查找Repeater控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Repeater FindRepeater(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Repeater>(ctl, id);
        }

        /// <summary>
        /// 查找GridView控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static GridView FindGridView(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<GridView>(ctl, id);
        }

        /// <summary>
        /// 查找DataList控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DataList FindDataList(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<DataList>(ctl, id);
        }

        /// <summary>
        /// 查找列表控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static BulletedList FindBulletedList(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<BulletedList>(ctl, id);
        }

        /// <summary>
        /// 查找Table控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Table FindTable(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<Table>(ctl, id);
        }

        public static TableRow FindTableRow(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<TableRow>(ctl, id);
        }

        public static TableCell FindTableCell(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<TableCell>(ctl, id);
        }

        #endregion

        #region 查找父控件
        public static T FindParent<T>(this System.Web.UI.Control ctl)
            where T : System.Web.UI.Control
        {
            ctl = ctl.Parent;
            while (!(ctl is T) && !(ctl is System.Web.UI.Page))
            {
                ctl = ctl.Parent;
            }
            return ctl as T;
        }

        /// <summary>
        /// 查找父控件名称为指定名称的控件,并转换为指定的类型
        /// </summary>
        /// <typeparam name="T">控件要转换的类型</typeparam>
        /// <param name="ctl"></param>
        /// <param name="id">要查找的控件的名称</param>
        /// <returns></returns>
        public static T FindParent<T>(this System.Web.UI.Control ctl, string id)
            where T : System.Web.UI.Control
        {
            ctl = ctl.Parent;
            while (!(ctl.ID == id) && !(ctl is System.Web.UI.Page))
            {
                ctl = ctl.Parent;
            }
            return ctl as T;
        }
        #endregion

        #region 查找HTML控件
        /// <summary>
        /// 查找HTML表格控件
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HtmlTable FindHtmlTable(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<HtmlTable>(ctl, id);
        }

        /// <summary>
        /// 查找HTML表格的行元素
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HtmlTableRow FindHtmlTableRow(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<HtmlTableRow>(ctl, id);
        }

        /// <summary>
        /// 查找HTML表格的单元格元素
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HtmlTableCell FindHtmlTableCell(this System.Web.UI.Control ctl, string id)
        {
            return FindControl<HtmlTableCell>(ctl, id);
        }
        #endregion

        /// <summary>
        /// 把一个控件转换为HTML表示的文本
        /// </summary>
        /// <param name="ctl"></param>
        /// <returns></returns>
        public static string ToHtml(this System.Web.UI.Control ctl)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            ctl.RenderControl(new System.Web.UI.HtmlTextWriter(new StringWriter(sb)));
            return sb.ToString();
        }
        #endregion

        #region ENUM
        public static string GetDescription(this System.Enum em)
        {
            DescriptionAttribute t = GetAttribute<DescriptionAttribute>(em);
            return t != null ? t.Description : string.Empty;
        }

        public static T GetAttribute<T>(this System.Enum em)
            where T : System.Attribute
        {
            FieldInfo fi = em.GetType().GetField(em.ToString());
            if (fi.IsDefined(typeof(T), true))
            {
                return (T)fi.GetCustomAttributes(typeof(T), true)[0];
            }
            return null;
        }

        public static bool IsIn<T>(this T current, T value, params T[] others)
            where T : struct
        {
            if (typeof(T).IsEnum)
            {
                bool flags = typeof(T).IsDefined(typeof(System.FlagsAttribute), true);
                return (flags ? (Convert.ToInt64(value) & Convert.ToInt64(current)) > 0 : Convert.ToInt64(current) == Convert.ToInt64(value)) ||
                    others.Exists(x => flags ? (Convert.ToInt64(x) & Convert.ToInt64(current)) > 0 : Convert.ToInt64(x) == Convert.ToInt64(current));
            }
            return value.Equals(current) || others.Exists(x => x.Equals(current));
        }
        #endregion

        #region LINQ
        public static IEnumerable ForEach<T>(this IEnumerable source, Action<T> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            foreach (T item in source)
            {
                action(item);
            }
            return source;
        }

        public static IEnumerable ForEach<T>(this IEnumerable source, Action<T, int> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            int i = 0;
            foreach (T item in source)
            {
                action(item, i);
                i++;
            }
            return source;
        }

        public static IEnumerable<O> ForEach<T, O>(this IEnumerable source, Func<T, O> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            List<O> result = new List<O>();
            foreach (T item in source)
            {
                result.Add(action(item));
            }
            return result;
        }

        public static IEnumerable<O> ForEach<T, O>(this IEnumerable source, Func<T, int, O> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            List<O> result = new List<O>();
            int i = 0;
            foreach (T item in source)
            {
                result.Add(action(item, i));
                i++;
            }
            return result;
        }

        public static bool NotExists<T>(this IEnumerable source, Predicate<T> match)
        {
            return !Exists(source, match);
        }

        public static T Find<T>(this IEnumerable source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            foreach (T item in source)
            {
                if (match(item))
                {
                    return item;
                }
            }
            return default(T);
        }

        public static List<T> FindAll<T>(this IEnumerable source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            List<T> result = new List<T>();
            foreach (T item in source)
            {
                if (match(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }

        public static bool Exists<T>(this IEnumerable source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            if (source is List<T>)
            {
                return ((List<T>)source).Exists(match);
            }
            foreach (T item in source)
            {
                if (match(item))
                {
                    return true;
                }
            }
            return false;
        }

        public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            foreach (T item in source)
            {
                action(item);
            }
            return source;
        }

        public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T, int> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            int i = 0;
            foreach (T item in source)
            {
                action(item, i);
                i++;
            }
            return source;
        }

        public static IEnumerable<O> ForEach<T, O>(this IEnumerable<T> source, Func<T, O> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            List<O> result = new List<O>();
            foreach (T item in source)
            {
                result.Add(action(item));
            }
            return result;
        }

        public static IEnumerable<O> ForEach<T, O>(this IEnumerable<T> source, Func<T, int, O> action)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            List<O> result = new List<O>();
            int i = 0;
            foreach (T item in source)
            {
                result.Add(action(item, i));
                i++;
            }
            return result;
        }

        public static bool NotExists<T>(this IEnumerable<T> source, Predicate<T> match)
        {
            return !Exists(source, match);
        }

        public static bool NotContains<T>(this IEnumerable<T> source, T item)
        {
            return !source.Contains(item);
        }

        public static T Find<T>(this IEnumerable<T> source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            foreach (T item in source)
            {
                if (match(item))
                {
                    return item;
                }
            }
            return default(T);
        }

        public static List<T> FindAll<T>(this IEnumerable<T> source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            List<T> result = new List<T>();
            foreach (T item in source)
            {
                if (match(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }

        public static bool Exists<T>(this IEnumerable<T> source, Predicate<T> match)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (match == null)
            {
                throw new ArgumentNullException("action");
            }
            if (source is List<T>)
            {
                return ((List<T>)source).Exists(match);
            }
            foreach (T item in source)
            {
                if (match(item))
                {
                    return true;
                }
            }
            return false;
        }

        public static bool Any<T>(this IEnumerable<T> source, Predicate<T> match)
        {
            foreach (var x in source)
            {
                if (!match(x))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 把一个列表合并为用指定地分隔符连接地字符串
        /// </summary>
        /// <param name="joins">要合并的列表</param>
        /// <param name="convert">格式化方法</param>
        /// <returns>合并后的字符串</returns>
        public static string JoinToString<T>(this IEnumerable<T> value, Func<T, string> convert = null, string separator = ",")
        {
            return PTA.Convert.ToStrictString<T>(value, convert, separator);
        }

        /// <summary>
        /// 把一个列表合并为用指定地分隔符连接地字符串
        /// </summary>
        /// <param name="joins">要合并的列表</param>
        /// <param name="start">开始位置</param>
        /// <param name="length">长度</param>
        /// <param name="convert">格式化方法</param>
        /// <returns>合并后的字符串</returns>
        public static string JoinToString<T>(this IEnumerable<T> value, int start, int length, Func<T, string> convert = null, string separator = ",")
        {
            return PTA.Convert.ToStrictString<T>(value, start, length, convert, separator);
        }

        /// <summary>
        /// 把一个对象添加到一个列表的最后面
        /// </summary>
        /// <typeparam name="T">要添加的对象的类型</typeparam>
        /// <param name="value">要添加的对象的值</param>
        /// <param name="list">要添加对象的列表</param>
        public static void AppendTo<T>(this T value, IList<T> list)
        {
            list.Add(value);
        }

        /// <summary>
        /// 把一个对象插入到一个列表的指定位置
        /// </summary>
        /// <typeparam name="T">要插入的对象的类型</typeparam>
        /// <param name="value">要插入的对象的值</param>
        /// <param name="list">要插入对象的列表</param>
        public static void InsertTo<T>(this T value, IList<T> list, int index)
        {
            list.Insert(index, value);
        }

        /// <summary>
        /// 把一个列表转换为一个数组,列表中的每一项都转换为指定的类型
        /// </summary>
        /// <typeparam name="T">列表项的类型</typeparam>
        /// <typeparam name="O">目标数组类型</typeparam>
        /// <param name="value">列表</param>
        /// <param name="convert">转换方法</param>
        /// <returns></returns>
        public static O[] ToArray<T, O>(this IList<T> value, Func<T, O> convert)
        {
            O[] result = new O[value.Count];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = convert(value[i]);
            }
            return result;
        }

        /// <summary>
        /// 把一个列表转换为一个数组,列表中的每一项都转换为指定的类型
        /// </summary>
        /// <typeparam name="T">列表项的类型</typeparam>
        /// <typeparam name="O">目标数组类型</typeparam>
        /// <param name="value">列表</param>
        /// <param name="convert">转换方法</param>
        /// <returns></returns>
        public static O[] ToArray<T, O>(this IEnumerable<T> value, Func<T, O> convert)
        {
            return value.ToList().ToArray(convert);
        }
        #endregion

        #region OBJECT
        /// <summary>
        /// 使用二进制序列化然后反序列化的方式为对象进行深度克隆
        /// </summary>
        /// <typeparam name="T">要克隆的对象类型</typeparam>
        /// <param name="source">要克隆的对象</param>
        /// <returns>返回克隆后的对象</returns>
        public static T DeepClone<T>(this T source)
            where T : class
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, source);
                ms.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(ms);
            }
        }
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToXml(this object o)
        {
            return PTA.Convert.ToXml(o).Replace(Environment.NewLine, "");
        }

        /// <summary>
        /// 将一个对象序列化为JSON字符串
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToJson(this object o)
        {
            return PTA.Convert.ToJson(o);
        }
        #region 字段
        public static bool HasField(this Type t, string name)
        {
            return t.GetField(name) != null;
        }

        public static bool HasField(this Type t, string name, BindingFlags flags)
        {
            return t.GetField(name, flags) != null;
        }

        public static T GetField<T>(this object o, string name)
        {
            return (T)o.GetType().GetField(name).GetValue(o);
        }

        public static T GetField<T>(this object o, string name, BindingFlags flags)
        {
            return (T)o.GetType().GetField(name, flags).GetValue(o);
        }

        public static void SetField(this object o, string name, object value)
        {
            o.GetType().GetField(name).SetValue(o, value);
        }
        public static void SetField(this object o, string name, BindingFlags flags, object value)
        {
            o.GetType().GetField(name, flags).SetValue(o, value);
        }
        #endregion

        #region 属性
        /// <summary>
        /// 查询指定的数据类型是否包含指定的属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasProperty(this Type t, string name)
        {
            return t.GetProperty(name) != null;
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定的属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <param name="flags">一个位屏蔽，由一个或多个指定搜索执行方式的 System.Reflection.BindingFlags 组成。- 或 -零，以返回 null</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasProperty(this Type t, string name, BindingFlags flags)
        {
            return t.GetProperty(name, flags) != null;
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称和返回值类型的属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <param name="returnType">属性的返回类型</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasProperty(this Type t, string name, Type returnType)
        {
            return t.GetProperty(name, returnType) != null;
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称的Get属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasGetProperty(this Type t, string name)
        {
            PropertyInfo pi = t.GetProperty(name);
            return pi != null && (pi.GetGetMethod() != null || pi.GetGetMethod(true) != null);
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称的Get属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasGetProperty(this Type t, string name, BindingFlags flags)
        {
            PropertyInfo pi = t.GetProperty(name, flags);
            return pi != null && (pi.GetGetMethod() != null || pi.GetGetMethod(true) != null);
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称的Get属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasGetProperty(this Type t, string name, Type returnType)
        {
            PropertyInfo pi = t.GetProperty(name, returnType);
            return pi != null && (pi.GetGetMethod() != null || pi.GetGetMethod(true) != null);
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称的Set属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasSetProperty(this Type t, string name)
        {
            PropertyInfo pi = t.GetProperty(name);
            return pi != null && (pi.GetSetMethod() != null || pi.GetSetMethod(true) != null);
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定名称的Set属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasSetProperty(this Type t, string name, BindingFlags flags)
        {
            PropertyInfo pi = t.GetProperty(name, flags);
            return pi != null && (pi.GetSetMethod() != null || pi.GetSetMethod(true) != null);
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定的属性
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">属性名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的属性</returns>
        public static bool HasProperty(this object o, string name)
        {
            return o.GetType().HasProperty(name);
        }

        /// <summary>
        /// 使用反射执行Get访问器
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">属性名称</param>
        /// <param name="bindingAttr">属性的类型</param>
        /// <returns>属性的返回值</returns>
        public static object GetProperty(this object o, string name)
        {
            if (o is System.Windows.Forms.Control)
            {
                System.Windows.Forms.Control ctl = (System.Windows.Forms.Control)o;
                return ctl.InvokeRequired ? ctl.Invoke(new Func<object, string, object>(GetProperty), new object[] { ctl, name })
                   : ctl.GetType().GetProperty(name).GetGetMethod().Invoke(ctl, null);
            }
            else
            {
                return o.GetType().GetProperty(name).GetValue(o, null);
            }
        }

        /// <summary>
        /// 使用反射执行Get访问器
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">属性名称</param>
        /// <param name="bindingAttr">属性的类型</param>
        /// <returns>属性的返回值</returns>
        public static object GetProperty(this object o, string name, Type returnType)
        {
            if (o is System.Windows.Forms.Control)
            {
                System.Windows.Forms.Control ctl = (System.Windows.Forms.Control)o;
                return ctl.InvokeRequired ? ctl.Invoke(new Func<object, string, Type, object>(GetProperty), new object[] { ctl, name, returnType })
                   : ctl.GetType().GetProperty(name, returnType).GetGetMethod().Invoke(ctl, null);
            }
            else
            {
                return o.GetType().GetProperty(name, returnType).GetValue(o, null);
            }
        }

        /// <summary>
        /// 使用反射执行Get访问器
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">属性名称</param>
        /// <returns>属性的返回值</returns>
        public static object GetProperty(this object o, string name, BindingFlags flags)
        {
            if (o is System.Windows.Forms.Control)
            {
                System.Windows.Forms.Control ctl = o as System.Windows.Forms.Control;
                return ctl.InvokeRequired ? ctl.Invoke(new Func<object, string, BindingFlags, object>(GetProperty), new object[] { ctl, name, flags })
                               : ctl.GetType().GetProperty(name).GetGetMethod((int)(flags | BindingFlags.NonPublic) > 0).Invoke(ctl, null);
            }
            else
            {
                return o.GetType().GetProperty(name, flags).GetValue(o, null);
            }
        }

        /// <summary>
        /// 使用反射执行Set访问器
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">属性名称</param>
        /// <param name="value">属性值</param>
        public static void SetProperty(this object o, string name, object value)
        {
            if (o is System.Windows.Forms.Control)
            {
                System.Windows.Forms.Control ctl = (System.Windows.Forms.Control)o;
                if (ctl.InvokeRequired)
                {

                    ctl.Invoke(new Action<System.Windows.Forms.Control, string, object>(SetProperty), new object[] { ctl, name, value });
                }
                else
                {
                    ctl.GetType().GetProperty(name).GetSetMethod().Invoke(ctl, new object[] { value });
                }
            }
            else
            {
                o.GetType().GetProperty(name).SetValue(o, value, null);
            }
        }

        /// <summary>
        /// 使用反射执行Set访问器
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">属性名称</param>
        /// <param name="value">属性值</param>
        /// <param name="bindingAttr">属性的类型</param>
        public static void SetProperty(this object o, string name, object value, BindingFlags flags)
        {
            if (o is System.Windows.Forms.Control)
            {
                System.Windows.Forms.Control ctl = (System.Windows.Forms.Control)o;
                if (ctl.InvokeRequired)
                {
                    ctl.Invoke(new Action<object, string, object, BindingFlags>(SetProperty), new object[] { ctl, name, value, flags });
                }
                else
                {
                    ctl.GetType().GetProperty(name).GetSetMethod((int)(flags | BindingFlags.NonPublic) > 0).Invoke(ctl, new object[] { value });
                }
            }
            else
            {
                o.GetType().GetProperty(name, flags).SetValue(o, value, null);
            }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 查询指定的数据类型是否包含指定的方法
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">方法名称</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的方法</returns>
        public static bool HasMethod(this Type t, string name)
        {
            return t.GetMethod(name) != null;
        }

        /// <summary>
        /// 查询指定的数据类型是否包含指定的方法
        /// </summary>
        /// <param name="t">数据类型</param>
        /// <param name="name">方法名称</param>
        /// <param name="flags">一个位屏蔽，由一个或多个指定搜索执行方式的 System.Reflection.BindingFlags 组成。- 或 -零，以返回 null</param>
        /// <returns>返回一个值,指定这个数据类型是否包含特定的方法</returns>
        public static bool HasMethod(this Type t, string name, BindingFlags flags)
        {
            return t.GetMethod(name, flags) != null;
        }

        /// <summary>
        ///  执行指定的方法
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">方法名称</param>
        /// <param name="parms">方法参数</param>
        /// <returns>方法执行后的返回值</returns>
        public static object ExecMethod(this object o, string name, object[] parms = null)
        {
            if (o.GetType().HasMethod(name))
            {
                if (o is System.Windows.Forms.Control)
                {
                    System.Windows.Forms.Control ctl = o as System.Windows.Forms.Control;
                    return ctl.InvokeRequired ? ctl.Invoke(new Func<object, string, object[], object>(ExecMethod), ctl, name, parms) : ctl.GetType().GetMethod(name).Invoke(ctl, parms);
                }
                else
                {
                    o.GetType().GetMethod(name).Invoke(o, parms);
                }
            }
            throw new Exception("方法未找到");
        }

        /// <summary>
        ///  执行指定的方法
        /// </summary>
        /// <param name="o">对象</param>
        /// <param name="name">方法名称</param>
        /// <param name="parms">方法参数</param>
        /// <param name="flags">属性的类型</param>
        /// <returns>方法执行后的返回值</returns>
        public static object ExecMethod(this object o, string name, BindingFlags flags, object[] parms = null)
        {
            if (o.GetType().HasMethod(name))
            {
                if (o is System.Windows.Forms.Control)
                {
                    System.Windows.Forms.Control ctl = o as System.Windows.Forms.Control;
                    return ctl.InvokeRequired ? ctl.Invoke(new Func<object, string, BindingFlags, object[], object>(ExecMethod), ctl, name, flags, parms) : ctl.GetType().GetMethod(name, flags).Invoke(ctl, parms);
                }
                else
                {
                    o.GetType().GetMethod(name, flags).Invoke(o, parms);
                }
            }
            throw new Exception("方法未找到");
        }
        #endregion

        #region 特性
        public static bool HasAttribute<A>(this ICustomAttributeProvider t, bool inherit = true)
            where A : Attribute
        {
            return t.IsDefined(typeof(A), inherit);
        }
        public static A GetAttribute<A>(this ICustomAttributeProvider t, bool inherit = true)
        {
            return (A)typeof(A).GetCustomAttributes(typeof(A), inherit)[0];
        }

        public static List<A> GetAttributes<A>(this ICustomAttributeProvider t, bool inherit = true)
        {
            List<A> result = new List<A>();
            typeof(A).GetCustomAttributes(typeof(A), true).ForEach(item => ((A)item).AppendTo(result));
            return result;
        }
        #endregion

        #region 事件
        public static bool HasEvent(this Type t, string name)
        {
            return t.GetEvent(name) != null;
        }
        public static bool HasEvent(this Type t, string name, BindingFlags flags)
        {
            return t.GetEvent(name, flags) != null;
        }
        public static void AddEventHandler(this object o, string name, Delegate handler)
        {
            if (o.GetType().HasEvent(name))
            {
                o.GetType().GetEvent(name).AddEventHandler(o, handler);
            }
            else
            {
                throw new Exception("未找到事件:" + name);
            }
        }
        public static void AddEventHandler(this object o, string name, BindingFlags flags, Delegate handler)
        {
            if (o.GetType().HasEvent(name, flags))
            {
                o.GetType().GetEvent(name, flags).AddEventHandler(o, handler);
            }
            else
            {
                throw new Exception("未找到事件:" + name);
            }
        }
        public static void RemoveEventHandler(this object o, string name, Delegate handler)
        {
            if (o.GetType().HasEvent(name))
            {
                o.GetType().GetEvent(name).RemoveEventHandler(o, handler);
            }
            else
            {
                throw new Exception("未找到事件:" + name);
            }
        }
        public static void RemoveEventHandler(this object o, string name, BindingFlags flags, Delegate handler)
        {
            if (o.GetType().HasEvent(name, flags))
            {
                o.GetType().GetEvent(name, flags).RemoveEventHandler(o, handler);
            }
            else
            {
                throw new Exception("未找到事件:" + name);
            }
        }
        public static void FireEvent(this object o, string name, object[] parms)
        {
            if (o.GetType().GetEvent(name).IsMulticast)
            {
                foreach (var item in ((MulticastDelegate)o.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public).GetValue(o)).GetInvocationList())
                {
                    item.Method.Invoke(item.Target, parms);
                }
            }
            else
            {
                ((MethodInfo)o.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public).GetValue(o)).Invoke(o, parms);
            }
        }
        public static void FireEvent(this object o, string name, BindingFlags flags, object[] parms)
        {
            if (o.GetType().GetEvent(name).IsMulticast)
            {
                foreach (var item in ((MulticastDelegate)o.GetType().GetField(name, flags).GetValue(o)).GetInvocationList())
                {
                    item.Method.Invoke(item.Target, parms);
                }
            }
            else
            {
                ((MethodInfo)o.GetType().GetField(name, flags).GetValue(o)).Invoke(o, parms);
            }
        }
        #endregion
        #endregion

        #region STRING
        public static bool IsIn(this string current, string value, params string[] others)
        {
            return value.Equals(current) || others.Exists(x => x.Equals(current));
        }

        public static int ToInt(this string value)
        {
            return int.Parse(value);
        }

        public static long ToLong(this string value)
        {
            return long.Parse(value);
        }

        public static double ToDouble(this string value)
        {
            return double.Parse(value);
        }

        public static float ToFloat(this string value)
        {
            return float.Parse(value);
        }

        public static Guid ToGuid(this string value)
        {
            return new Guid(value);
        }

        public static DateTime ToDateTime(this string value)
        {
            return Convert.ToDateTime(value);
        }

        public static DateTime ToDateTime(this string value, string format)
        {
            return DateTime.ParseExact(value, format, new System.Globalization.CultureInfo("zh-cn"));
        }

        public static List<T> ToList<T>(this string value, Func<string, T> convert)
        {
            List<T> result = new List<T>();
            if (String.IsNullOrWhiteSpace(value))
            {
                return result;
            }
            string[] values = value.Split(',');
            foreach (var item in values)
            {
                if (!String.IsNullOrWhiteSpace(item))
                {
                    result.Add(convert(item));
                }
            }
            return result;
        }

        public static string ToSimpleChinese(this string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return string.Empty;
            }
            return TextConvert(value, ChineseConversionDirection.繁体转简体);

        }

        public static string ToTraditionalChinese(this string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return string.Empty;
            }
            return TextConvert(value, ChineseConversionDirection.简体转繁体);
        }

        public static string Compress(this string value)
        {
            using (MemoryStream ms = new MemoryStream())
            using (System.IO.Compression.GZipStream Compress = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress))
            {
                var bytes = System.Text.Encoding.UTF8.GetBytes(value);
                Compress.Write(bytes, 0, bytes.Length);
                Compress.Close();
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        public static string Decompress(this string value)
        {
            using (MemoryStream ms = new MemoryStream())
            using (System.IO.Compression.GZipStream Compress = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress))
            {
                var bytes = Convert.FromBase64String(value);
                Compress.Write(bytes, 0, bytes.Length);
                Compress.Close();
                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        public static bool IgnoreEquals(this string current, string value)
        {
            return current.Equals(value, StringComparison.OrdinalIgnoreCase);
        }
        #region 简繁转换

        private static string TextConvert(string text, ChineseConversionDirection direction)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            OfficeConversionEngine engine = OfficeConversionEngine.Create();
            if (engine != null)
            {
                return engine.TCSCConvert(text, direction);
            }
            int dwMapFlags = (direction == ChineseConversionDirection.繁体转简体) ? 0x2000000 : 0x4000000;
            int cb = (text.Length * 2) + 2;
            IntPtr lpDestStr = Marshal.AllocHGlobal(cb);
            NativeMethods.LCMapString(0x804, (uint)dwMapFlags, text, -1, lpDestStr, cb);
            string str = Marshal.PtrToStringUni(lpDestStr);
            Marshal.FreeHGlobal(lpDestStr);
            return str;
        }

        /// <summary>
        /// 简繁转换方向
        /// </summary>
        public enum ChineseConversionDirection
        {
            /// <summary>
            /// 简体到繁体转换
            /// </summary>
            简体转繁体,

            /// <summary>
            /// 繁体到简体转换
            /// </summary>
            繁体转简体
        }

        internal static class NativeMethods
        {
            public const uint LCMAP_SIMPLIFIED_CHINESE = 0x2000000;
            public const uint LCMAP_TRADITIONAL_CHINESE = 0x4000000;
            public const int zh_CN = 0x804;

            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("KERNEL32.DLL", SetLastError = true)]
            public static extern bool FreeLibrary(HandleRef hModule);
            [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode)]
            public static extern int LCMapString(int Locale, uint dwMapFlags, [MarshalAs(UnmanagedType.LPTStr)] string lpSrcStr, int cchSrc, IntPtr lpDestStr, int cchDest);
            [DllImport("KERNEL32.DLL", CharSet = CharSet.Unicode)]
            public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPTStr)] string lpFileName);
            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("MSTR2TSC.DLL", CharSet = CharSet.Unicode)]
            public static extern bool TCSCConvertText([MarshalAs(UnmanagedType.LPTStr)] string pwszInput, int cchInput, out IntPtr ppwszOutput, out int pcchOutput, ChineseConversionDirection dwDirection, [MarshalAs(UnmanagedType.Bool)] bool fCharBase, [MarshalAs(UnmanagedType.Bool)] bool fLocalTerm);
            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("MSTR2TSC.DLL")]
            public static extern bool TCSCFreeConvertedText(IntPtr pv);
            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("MSTR2TSC.DLL")]
            public static extern bool TCSCInitialize();
            [return: MarshalAs(UnmanagedType.Bool)]
            [DllImport("MSTR2TSC.DLL")]
            public static extern bool TCSCUninitialize();
        }

        internal class OfficeConversionEngine
        {
            private static string MSOPath;
            private static string Mstr2tscPath;

            static OfficeConversionEngine()
            {
                string str = null;
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\InstallRoot");
                if (key != null)
                {
                    str = Convert.ToString(key.GetValue("Path"), (IFormatProvider)null);
                }
                Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\FilesPaths");
                if (key2 != null)
                {
                    MSOPath = Convert.ToString(key2.GetValue("mso.dll"), (IFormatProvider)null);
                }
                if (!string.IsNullOrEmpty(str))
                {
                    Mstr2tscPath = Path.Combine(str, @"ADDINS\MSTR2TSC.DLL");
                }
                if (string.IsNullOrEmpty(Mstr2tscPath) || !File.Exists(Mstr2tscPath))
                {
                    Mstr2tscPath = null;
                }
            }

            private OfficeConversionEngine()
            {
            }

            public static OfficeConversionEngine Create()
            {
                if (!string.IsNullOrEmpty(MSOPath) && !string.IsNullOrEmpty(Mstr2tscPath))
                {
                    return new OfficeConversionEngine();
                }
                return null;
            }

            public string TCSCConvert(string input, ChineseConversionDirection direction)
            {
                string str2;
                IntPtr zero = IntPtr.Zero;
                IntPtr handle = IntPtr.Zero;
                try
                {
                    IntPtr ptr3;
                    int num;
                    zero = NativeMethods.LoadLibrary(MSOPath);
                    handle = NativeMethods.LoadLibrary(Mstr2tscPath);
                    if (!NativeMethods.TCSCInitialize())
                    {
                        return null;
                    }
                    string str = null;
                    if (NativeMethods.TCSCConvertText(input, input.Length, out ptr3, out num, direction, false, true))
                    {
                        str = Marshal.PtrToStringUni(ptr3);
                        NativeMethods.TCSCFreeConvertedText(ptr3);
                    }
                    NativeMethods.TCSCUninitialize();
                    str2 = str;
                }
                finally
                {
                    if (handle != IntPtr.Zero)
                    {
                        NativeMethods.FreeLibrary(new HandleRef(this, handle));
                    }
                    if (zero != IntPtr.Zero)
                    {
                        NativeMethods.FreeLibrary(new HandleRef(this, zero));
                    }
                }
                return str2;
            }
        }
        #endregion
        #endregion

        #region NameValueCollection
        public static int GetInt(this NameValueCollection collection, string name, int defaultValue = 0)
        {
            string value = collection[name];
            return Convert.IsInt(value) ? value.ToInt() : defaultValue;
        }

        public static long GetLong(this NameValueCollection collection, string name, long defaultValue = 0)
        {
            string value = collection[name];
            return Convert.IsLong(value) ? value.ToLong() : defaultValue;
        }

        public static double GetDouble(this NameValueCollection collection, string name, double defaultValue = 0)
        {
            string value = collection[name];
            return Convert.IsDouble(value) ? value.ToDouble() : defaultValue;
        }

        public static float GetFloat(this NameValueCollection collection, string name, float defaultValue = 0)
        {
            string value = collection[name];
            return Convert.IsFloat(value) ? value.ToFloat() : defaultValue;
        }

        public static Guid GetGuid(this NameValueCollection collection, string name, Guid defaultValue = default(Guid))
        {
            string value = collection[name];
            return Convert.IsGuid(value) ? value.ToGuid() : defaultValue;
        }

        public static DateTime GetDate(this NameValueCollection collection, string name, DateTime defaultValue = default(DateTime))
        {
            string value = collection[name]; ;
            return Convert.IsDate(value) ? value.ToDateTime() : defaultValue;
        }

        public static DateTime GetDateTime(this NameValueCollection collection, string name, DateTime defaultValue = default(DateTime))
        {
            string value = collection[name]; ;
            return Convert.IsDateTime(value) ? value.ToDateTime() : defaultValue;
        }

        #endregion

        #region HttpRequest
        public static int GetQueryInt(this HttpRequest request, string name, int defaultValue = 0)
        {
            return request.QueryString.GetInt(name, defaultValue);
        }

        public static long GetQueryLong(this HttpRequest request, string name, long defaultValue = 0)
        {
            return request.QueryString.GetLong(name, defaultValue);
        }

        public static double GetQueryDouble(this HttpRequest request, string name, double defaultValue = 0)
        {
            return request.QueryString.GetDouble(name, defaultValue);
        }

        public static float GetQueryFloat(this HttpRequest request, string name, float defaultValue = 0)
        {
            return request.QueryString.GetFloat(name, defaultValue);
        }

        public static Guid GetQueryGuid(this HttpRequest request, string name, Guid defaultValue = default(Guid))
        {
            return request.QueryString.GetGuid(name, defaultValue);
        }

        public static DateTime GetQueryDate(this HttpRequest request, string name, DateTime defaultValue = default(DateTime))
        {
            return request.QueryString.GetDate(name, defaultValue);
        }

        public static DateTime GetQueryDateTime(this HttpRequest request, string name, DateTime defaultValue = default(DateTime))
        {
            return request.QueryString.GetDateTime(name, defaultValue);
        }

        public static int GetFormInt(this HttpRequest request, string name, int defaultValue = 0)
        {
            return request.Form.GetInt(name, defaultValue);
        }

        public static long GetFormLong(this HttpRequest request, string name, long defaultValue = 0)
        {
            return request.Form.GetLong(name, defaultValue);
        }

        public static double GetFormDouble(this HttpRequest request, string name, double defaultValue = 0)
        {
            return request.Form.GetDouble(name, defaultValue);
        }

        public static float GetFormFloat(this HttpRequest request, string name, float defaultValue = 0)
        {
            return request.Form.GetFloat(name, defaultValue);
        }

        public static Guid GetFormGuid(this HttpRequest request, string name, Guid defaultValue = default(Guid))
        {
            return request.Form.GetGuid(name, defaultValue);
        }

        public static DateTime GetFormDate(this HttpRequest request, string name, DateTime defaultValue = default(DateTime))
        {
            return request.Form.GetDate(name, defaultValue);
        }

        public static DateTime GetFormDateTime(this HttpRequest request, string name, DateTime defaultValue = default(DateTime))
        {
            return request.Form.GetDateTime(name, defaultValue);
        }

        public static ClientInfo GetClientInfo(this HttpRequest request)
        {
            return ClientInfo.Parse(request);
        }

        /// <summary>
        /// 用户的客户端信息
        /// </summary>
        public class ClientInfo
        {
            private string browserName = string.Empty;
            /// <summary>
            /// 浏览器名称
            /// </summary>
            public string BrowserName
            {
                get
                {
                    return this.browserName ?? string.Empty;
                }
            }

            private string browserVersion = string.Empty;
            /// <summary>
            /// 浏览器版本
            /// </summary>
            public string BrowserVersion
            {
                get
                {
                    return this.browserVersion ?? string.Empty;
                }
            }

            private string ipAdress = string.Empty;
            /// <summary>
            /// 用户IP地址
            /// </summary>
            public string IPAddress
            {
                get
                {
                    return this.ipAdress ?? string.Empty;
                }
            }

            private string osName;
            /// <summary>
            /// 操作系统名称
            /// </summary>
            public string OSName
            {
                get
                {
                    return this.osName ?? string.Empty;
                }
            }

            private string osVersion;
            /// <summary>
            /// 操作系统版本
            /// </summary>
            public string OSVersion
            {
                get
                {
                    return this.osVersion ?? string.Empty;
                }
            }

            private DateTime accessTime;
            /// <summary>
            /// 用户访问时间
            /// </summary>
            public DateTime AccessTime
            {
                get
                {
                    return this.accessTime;
                }
            }

            /// <summary>
            /// 根据request对象生成客户端对象
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            public static ClientInfo Parse(System.Web.HttpRequest request)
            {
                ClientInfo client = new ClientInfo();
                client.accessTime = DateTime.Now;
                client.browserName = request.Browser.Browser;
                client.browserVersion = request.Browser.Version;
                try
                {
                    client.ipAdress = request.UserHostAddress;
                    if (string.IsNullOrEmpty(client.ipAdress))
                    {
                        client.ipAdress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];//获取包括使用了代理服务器的地址列表。
                    }
                    if (string.IsNullOrEmpty(client.ipAdress))
                    {
                        client.ipAdress = request.ServerVariables["REMOTE_ADDR"];//最后一个代理服务器地址。
                    }
                    if (string.IsNullOrEmpty(client.ipAdress))
                    {
                        client.ipAdress = request.UserHostAddress;
                    }
                }
                catch
                {
                    client.ipAdress = "UnKnown";
                }

                client.osName = request.Browser.Platform;
                string userAgent = request.UserAgent.ToLower();
                if (userAgent.Contains("nt 6.0"))
                {
                    client.osVersion = "Windows Vista/Server 2008";
                }
                else if (userAgent.Contains("nt 5.2"))
                {
                    client.osVersion = "Windows Server 2003";
                }
                else if (userAgent.Contains("nt 5.1"))
                {
                    client.osVersion = "Windows XP";
                }
                else if (userAgent.Contains("nt 5"))
                {
                    client.osVersion = "Windows 2000";
                }
                else if (userAgent.Contains("nt 4"))
                {
                    client.osVersion = "Windows NT4";
                }
                else if (userAgent.Contains("me"))
                {
                    client.osVersion = "Windows Me";
                }
                else if (userAgent.Contains("98"))
                {
                    client.osVersion = "Windows 98";
                }
                else if (userAgent.Contains("95"))
                {
                    client.osVersion = "Windows 95";
                }
                else if (userAgent.Contains("mac"))
                {
                    client.osVersion = "Mac";
                }
                else if (userAgent.Contains("unix"))
                {
                    client.osVersion = "UNIX";
                }
                else if (userAgent.Contains("linux"))
                {
                    client.osVersion = "Linux";
                }
                else if (userAgent.Contains("sunos"))
                {
                    client.osVersion = "SunOS";
                }

                return client;
            }
        }
        #endregion

        #region ViewState
        public static T Get<T>(this IDictionary value, string name, T defaultValue = default(T))
        {
            if (value[name] != null)
            {
                return (T)value[name];
            }
            return defaultValue;
        }
        public static string GetString(this IDictionary value, string name, string defaultValue = default(string))
        {
            return Get<string>(value, name, defaultValue);
        }
        public static int GetInt(this IDictionary value, string name, int defaultValue = 0)
        {
            return Get<int>(value, name, defaultValue);
        }
        public static DateTime GetDateTime(this IDictionary value, string name, DateTime defaultValue = default(DateTime))
        {
            return Get<DateTime>(value, name, defaultValue);
        }
        public static long GetLong(this IDictionary value, string name, long defaultValue = 0)
        {
            return Get<long>(value, name, defaultValue);
        }
        public static double GetDoule(this IDictionary value, string name, double defaultValue = default(double))
        {
            return Get<double>(value, name, defaultValue);
        }
        public static float GetFloat(this IDictionary value, string name, float defaultValue = default(float))
        {
            return Get<float>(value, name, defaultValue);
        }
        public static Guid GetGuid(this IDictionary value, string name, Guid defaultValue = default(Guid))
        {
            return Get<Guid>(value, name, defaultValue);
        }
        public static bool GetBool(this IDictionary value, string name, bool defaultValue = default(bool))
        {
            return Get<bool>(value, name, defaultValue);
        }
        #endregion

        #region StringBuilder
        public static StringBuilder Append(this System.Text.StringBuilder sb, char c, int repeatCount, string value)
        {
            return sb.Append(c, repeatCount).Append(value);
        }
        public static StringBuilder Append(this System.Text.StringBuilder sb, char c, int repeatCount, object value)
        {
            return sb.Append(c, repeatCount).Append(value);
        }
        public static StringBuilder Append(this System.Text.StringBuilder sb, char c, int repeatCount, string format, params object[] args)
        {
            return sb.Append(c, repeatCount).AppendFormat(format, args);
        }
        public static StringBuilder AppendFormatLine(this System.Text.StringBuilder sb, string format, params object[] args)
        {
            return sb.AppendFormat(format, args).AppendLine();
        }
        public static StringBuilder AppendFormatLine(this System.Text.StringBuilder sb, char c, int repeatCount, string format, params object[] args)
        {
            return sb.Append(c, repeatCount).AppendFormatLine(format, args);
        }
        public static StringBuilder InsertFormat(this System.Text.StringBuilder sb, int index, string format, params object[] args)
        {
            return sb.Insert(index, string.Format(format, args));
        }
        public static StringBuilder InsertFormat(this System.Text.StringBuilder sb, int index, char c, int repeatCount, string format, params object[] args)
        {
            return sb.InsertFormat(index, format, args).Insert(0, new string(c, repeatCount));
        }
        public static StringBuilder InsertFormatLine(this System.Text.StringBuilder sb, int index, string format, params object[] args)
        {
            return sb.Insert(index, Environment.NewLine).Insert(index, string.Format(format, args));
        }
        public static StringBuilder InsertFormatLine(this System.Text.StringBuilder sb, int index, char c, int repeatCount, string format, params object[] args)
        {
            return sb.Insert(index, Environment.NewLine).InsertFormat(index, format, args).Insert(0, new string(c, repeatCount));
        }
        #endregion

        #region DateTime

        public static int GetHalfYear(this DateTime dt)
        {
            return dt.Year * 100 + (dt.Month + 5) / 2;
        }
        public static int GetYearMonth(this DateTime dt)
        {
            return dt.Year * 100 + dt.Month;
        }
        public static int GetYearMonthDay(this DateTime dt)
        {
            return dt.Year * 10000 + dt.Month * 100 + dt.Day;
        }
        public static int GetYearMonthDayHour(this DateTime dt)
        {
            return dt.Year * 1000000 + dt.Month * 10000 + dt.Day * 100 + dt.Hour;

        }
        public static string ToString(this DateTime dt, DateFormatType format = DateFormatType.DateTime, string minmaxexpr = "--")
        {
            return (dt == DateTime.MinValue || dt == DateTime.MaxValue) ? minmaxexpr : dt.ToString(format.GetDescription());

        }
        public static string ToDateString(this DateTime dt, string minmaxexpr = "--")
        {
            return dt.ToString(DateFormatType.Date, minmaxexpr);
        }
        public static string ToTimeString(this DateTime dt, string minmaxexpr = "--")
        {
            return dt.ToString(DateFormatType.Time, minmaxexpr);
        }
        public static string ToDateTimeString(this DateTime dt, string minmaxexpr = "--")
        {
            return dt.ToString(DateFormatType.DateTime, minmaxexpr);
        }
        public static ChineseDayOfWeek GetDayOfWeek(this DateTime dt)
        {
            return PTA.Convert.ChangeType<ChineseDayOfWeek>(dt.DayOfWeek);
        }
        /// <summary>
        /// 中文的星期列表
        /// </summary>
        public enum ChineseDayOfWeek
        {
            /// <summary>
            /// 星期日
            /// </summary>
            星期日 = 0,

            /// <summary>
            /// 星期一
            /// </summary>
            星期一 = 1,

            /// <summary>
            /// 星期二
            /// </summary>
            星期二 = 2,

            /// <summary>
            /// 
            /// </summary>
            星期三 = 3,

            /// <summary>
            /// 星期四
            /// </summary>
            星期四 = 4,

            /// <summary>
            /// 星期五
            /// </summary>
            星期五 = 5,

            /// <summary>
            /// 星期六
            /// </summary>
            星期六 = 6

        }
        public enum DateTimeSpan
        {
            [Description("按年统计")]
            年 = 1,

            [Description("按上半年/下半年统计")]
            半年 = 2,

            [Description("按季度统计")]
            季 = 3,

            [Description("按月统计")]
            月 = 4,

            [Description("按日期统计")]
            日 = 5,

            [Description("按小时统计")]
            时 = 6,
        }
        #endregion

        #region MenuItem
        public static MenuItem Clone(this MenuItem source)
        {
            var result = new MenuItem
            {
                Enabled = source.Enabled,
                ImageUrl = source.ImageUrl,
                NavigateUrl = source.NavigateUrl,
                PopOutImageUrl = source.PopOutImageUrl,
                Selectable = source.Selectable,
                Selected = source.Selected,
                SeparatorImageUrl = source.SeparatorImageUrl,
                Target = source.Target,
                Text = source.Text,
                ToolTip = source.ToolTip,
                Value = source.Value
            };
            source.ChildItems.ForEach<MenuItem>(x => result.ChildItems.Add(x.Clone()));
            return result;
        }
        #endregion

        #region Attribute
        #endregion

        #region DataSet DataTable
        /// <summary>
        /// 将一个DataSet对象的数据序列化为XML字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToXml(this System.Data.DataSet value)
        {
            StringBuilder sb = new StringBuilder();
            using (System.IO.TextWriter tw = new System.IO.StringWriter(sb))
            {
                value.WriteXml(tw);
                return sb.ToString();
            }
        }

        /// <summary>
        /// 将一个DataTable对象序列化为XML字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToXml(this System.Data.DataTable value)
        {
            StringBuilder sb = new StringBuilder();
            using (System.IO.TextWriter tw = new System.IO.StringWriter(sb))
            {
                value.WriteXml(tw);
                return sb.ToString();
            }
        }
        #endregion

        #region Number
        public static string ToComma(this int value)
        {
            return string.Format("{0:N0}",value);
        }
        public static string ToComma(this short value)
        {
            return string.Format("{0:N0}", value);
        }
        public static string ToComma(this long value)
        {
            return string.Format("{0:N0}", value);
        }

        public static string ToComma(this float value, int digits = 2)
        {
            return string.Format(string.Format("{{0:N{0}}}", digits), value);
        }
        public static string ToComma(this double value, int digits = 2)
        {
            return string.Format(string.Format("{{0:N{0}}}", digits), value);
        }
        public static string ToComma(this decimal value, int digits = 2)
        {
            return string.Format(string.Format("{{0:N{0}}}", digits), value);
        }

        public static string ToDigits(this float value, int digits = 2)
        {
            return string.Format(string.Format("{{0:F{0}}}", digits), value);
        }
        public static string ToDigits(this double value, int digits = 2)
        {
            return string.Format(string.Format("{{0:F{0}}}", digits), value);
        }
        public static string ToDigits(this decimal value, int digits = 2)
        {
            return string.Format(string.Format("{{0:F{0}}}", digits), value);
        }
        #endregion
    }
}
